package cloud.tianai.ram.policy.server.permission.impl;

import cloud.tianai.ram.policy.common.model.dto.Statement;
import cloud.tianai.ram.policy.common.model.dto.Match;
import cloud.tianai.ram.policy.common.handler.StandardMatchHandler;
import cloud.tianai.ram.policy.common.model.dto.Action;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 天爱有情
 * @date 2022/3/23 16:34
 * @Description 可以从spring中获取 StandardMatchHandler
 */
public class SpringPermissionHandler extends DefaultPermissionHandler {
    private BeanFactory beanFactory;
    private boolean initialized = false;

    public SpringPermissionHandler(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    @Override
    public Match handle(Action action, Statement statement) {
        if (!initialized) {
            init();
            initialized = true;
        }
        return super.handle(action, statement);
    }

    private void init() {
        String[] beanNames = ((ConfigurableListableBeanFactory) beanFactory).getBeanNamesForType(StandardMatchHandler.class);
        List<StandardMatchHandler> supportedHandlers = new ArrayList<StandardMatchHandler>();
        for (String beanName : beanNames) {
            StandardMatchHandler bean = (StandardMatchHandler)beanFactory.getBean(beanName);
            if (bean == this) {
                // 跳过自己
                break;
            }
            supportedHandlers.add(bean);
        }
        addStandardMatchHandler(supportedHandlers);
    }
}
